<template>
  <div>
    <!-- 封装的添加部门和编辑部门弹出层 -->
    <!-- 父传子去打开弹出层 -->
    <!-- 点击新增、编辑是，把visible改为true -->

    <!-- <el-dialog :visible="visible" @close="$emit('close',false)"> -->
    <!-- :title="formData.id?'编辑部门': '新增部门'" 判断点击的弹出框标题，有id的是编辑 -->
    <el-dialog
      :title="formData.id?'编辑部门': '新增部门'"
      width="600px"
      :visible="visible"
      @close="$emit('update:visible', false)"
    >
      <!-- <H1>我是弹出层</H1> -->
      <el-form
        ref="formRef"
        label-width="140px"
        size="mini"
        :model="formData"
        :rules="rules"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select
            v-model="formData.managerId"
            placeholder="请输入负责人"
            style="width: 100%"
          >
            <el-option
              v-for="item in managerData"
              :key="item.id"
              :value="item.id"
              :label="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="formData.introduce"
            placeholder="1-100个字符"
            type="textarea"
          />
        </el-form-item>

        <el-form-item>
          <el-row type="flex" justify="center">
            <el-button type="primary" @click="onSubmit">确认</el-button>
            <el-button @click="$emit('update:visible', false)">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAddDspApi,
  getDepDetailApi,
  getDespAPi,
  getManagerDspApi,
  updateDepApi
} from '@/api/department'
// 表单校验 定义数据 设置规则 绑定内容
// 业务校验
// 自定义校验，发请求查询数据，判断输入的数据跟请求回来的数据是否相等，相等就提示用户重复，不相等就添加成功
// 获取下拉列表部门负责人数据  发请求 进入页面发请求，拿数据，定义数据 for循环渲染列表
// 封装新增部门api 父组件传定义的pid 调用接口拼接定义的pid
export default {
  props: {
    visible: Boolean,
    pid: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      formData: {
        name: '',
        code: '',
        introduce: '',
        managerId: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度是2-10个字符', trigger: 'blur' },
          {
            validator: async(rules, value, callback) => {
              let { data } = await getDespAPi()
              // console.log(res)
              // const hasOldName = res.data.findIndex(v => v.name === value) >= 0
              // 先过滤掉本身，点击编辑的时候不要校验当前
              if (this.formData.id) {
                data = data.filter(v => v.id !== this.formData.id)
                console.log(data)
              }
              if (data.some((v) => v.name === value)) {
                callback(new Error('部门名称不能重复'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度是2-10个字符', trigger: 'blur' },
          {
            validator: async(rules, value, callback) => {
              let { data } = await getDespAPi()
              // console.log(res)
              // const hasOldName = res.data.findIndex(v => v.code === value) >= 0
              // console.log(hasOldName)
              if (this.formData.id) {
                data = data.filter(v => v.id !== this.formData.id)
                // console.log(data)
              }
              if (data.some((v) => v.code === value)) {
                callback(new Error('部门编码不能重复'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度是2-10个字符', trigger: 'blur' }
        ],
        managerId: [
          {
            required: true,
            message: '部门负责人名字不能为空',
            trigger: 'blur'
          }
        ]
      },
      managerData: {}
    }
  },
  // 重置表单
  watch: {
    visible(newVisible) {
      if (!newVisible) {
        this.$refs.formRef.resetFields()
        // 清空数据（因为有写字段没有做过校验）
        this.formData = {
          name: '',
          code: '',
          introduce: '',
          managerId: ''
        }
      }
    }
  },
  async created() {
    const res = await getManagerDspApi()
    // console.log(res.data)
    this.managerData = res.data
  },
  methods: {
    // 定义编辑方法，获取接口请求
    async onEdit(id) {
      const res = await getDepDetailApi(id)
      // console.log(res)
      this.formData = res.data
    },
    // 做编辑  根据id 封装api 判断是否有id 有id是编辑 没有id是新增模态框
    async onSubmit() {
      await this.$refs.formRef.validate()
      if (this.formData.id) {
        await updateDepApi(this.formData)
        console.log(this.formData)
      } else {
        await getAddDspApi({ ...this.formData, pid: this.pid })
      }
      // 调用接口

      // 提示用户
      this.$message.success(this.formData.id ? '编辑成功' : '新增成功')
      // 关闭页面
      this.$emit('update:visible', false)
      // 提醒父组件刷新页面
      this.$emit('onSuccess')
    }
  }
}
</script>

<style>
</style>
